package csl.blog.server.config.mq;

import csl.blog.server.common.AsyncEventAccessBuilder;
import csl.blog.server.common.MessageHandle;
import csl.blog.server.common.model.BaseMessage;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;

/**
 * @Description: TODO 生产者配置
 * @author: 隔山海
 * @date: 2021年10月08日 16:56
 */
@Configuration
public class ProduceRabbitConfig {

    @Value("${mq.address}")
    private String addressed;

    @Value("${mq.username}")
    private String username;

    @Value("${mq.password}")
    private String password;

    @Value("${mq.virtual.host}")
    private String virtualHost;

    @Value("${mq.event.exchange}")
    private String eventExchange;

    @Value("${mq.event.dead.exchange}")
    private String eventDeadExchange;

    @Value("${mq.routing.key}")
    private String routingKey;

    @Value("${mq.async.event}")
    private String eventQueue;

    @Value("${mq.type}")
    private String type;

    @Bean
    public ConnectionFactory connectionFactory() {
        CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory();
        cachingConnectionFactory.setAddresses(addressed);
        cachingConnectionFactory.setUsername(username);
        cachingConnectionFactory.setPassword(password);
        cachingConnectionFactory.setVirtualHost(virtualHost);
        //发送确认
        cachingConnectionFactory.setPublisherConfirms(true);
        //路由失败回调
        cachingConnectionFactory.setPublisherReturns(true);
        return cachingConnectionFactory;
    }

    /**
     * 异步任务Handler
     */
    @Bean
    public <T extends BaseMessage> MessageHandle<T> eventSender() throws IOException {
        AsyncEventAccessBuilder<T> asyncEventAccessBuilder = new AsyncEventAccessBuilder<>();
        return asyncEventAccessBuilder.buildMessageSender(
                eventExchange,
                eventDeadExchange,
                routingKey,
                eventQueue,
                type);
    }
}
